package cn.tedu.charging.order.config;

import cn.tedu.charging.order.mqtt.MqttConsumer;
import cn.tedu.charging.order.mqtt.MqttContextHook;
import org.eclipse.paho.client.mqttv3.MqttCallback;
import org.eclipse.paho.client.mqttv3.MqttClient;
import org.eclipse.paho.client.mqttv3.MqttConnectOptions;
import org.eclipse.paho.client.mqttv3.persist.MemoryPersistence;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;

import java.util.UUID;

/**
 * 配置类，构建一个emqx底层的客户端对象，类似在rabbitmq床架你的Connection
 * 所有程序代码，实现消息发送、消费，都是通过连接对象完成
 */
@Configuration
public class MqttCliConfig {
    @Value("${charging.emqx.address}")
    private String address;
    @Value("${charging.emqx.username}")
    private String username;
    @Value("${charging.emqx.password}")
    private String password;
    @Autowired
    private MqttContextHook mqttContextHook;

    @Bean
    public MqttClient init() {
        MqttClient mqttClient = null;
        try {
            // 初始化client对象，向其提供必要的连接属性：ip 端口号 用户名 密码 虚拟主机
            // 每一个客户端都需要一个唯一id值
            String uuid = UUID.randomUUID().toString();
            // 每次启动都会在本地存储一个日志锁文件，需要将该文件的内容放置到内存中 -> new MemoryPersistence()
            mqttClient = new MqttClient(address, uuid, new MemoryPersistence());
            // 需要在客户端船回家年完成之后设置选择属性，以完成功能需要
            MqttConnectOptions options = new MqttConnectOptions();
            // 必须填写的授权认证（用户名密码）
            options.setUserName(username);
            options.setPassword(password.toCharArray());
            //通过选项建立client客户端和服务端连接
            MqttCallback callback = new MqttConsumer(mqttClient,mqttContextHook);
//            MqttCallback callback = new MqttConsumer();
            mqttClient.setCallback(callback);  // 添加消费者回调对象
            mqttClient.connect(options);
            // ToDO 必须填写的属性 消费回调对象 开发消费者
        } catch (Exception e) {
            e.printStackTrace();
            System.out.println("创建连接失败");
        }
        return mqttClient;
    }
}
